<template>
  <el-dialog
  title="用户注册"
  :visible.sync="dialogVisible"
  width="600px"
  center
  :before-close="handleClose">
   <el-form :model="form" :rules="rules" ref="form" label-width="80px" label-position="left">
    <el-form-item label="头像" prop="avatar">
        <el-upload
        class="avatar-uploader"
        :action="avatarurl"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :data='imageObj'>
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </el-form-item>
        <el-form-item prop="username" label="昵称">
        <el-input  v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
        <el-input  v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="手机">
        <el-input  v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
        <el-input  v-model="form.password"></el-input>
        </el-form-item>
        <el-row>
        <el-col :span="16">
        <el-form-item label="图形码" prop="code">
        <el-input v-model="form.code" ></el-input>
      </el-form-item>
       </el-col>
        <el-col :span="7" style="margin-left:10px;">
        <img :src="getCaptcha" alt="" @click="getCode" style="width:100%;height:40px">
        </el-col>
        </el-row>
        <el-row>
        <el-col :span="16">
        <el-form-item label="验证码" prop="rcode">
        <el-input v-model="form.rcode" ></el-input>
      </el-form-item>
       </el-col>
        <el-col :span="7" style="margin-left:10px;">
       <el-button style="width:140px" @click="getrcode">获取用户验证码</el-button>
        </el-col>
        </el-row>
    </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="register">确 定</el-button>
  </span>
</el-dialog>
</template>
<script>
export default {
  name: 'register',
  data () {
    return {
    // 上传图片的地址
      avatarurl: process.env.VUE_APP_BASEURL + '/uploads',
      // 预览图片的地址
      imageUrl: '',
      imageObj: {
        image: null
      },
      getCaptcha: process.env.VUE_APP_BASEURL + '/captcha?type=sendsms', // 图形码地址
      dialogVisible: false,
      form: {
        avatar: '',
        username: '',
        phone: '',
        email: '',
        password: '',
        code: '',
        rcode: ''
      },
      rules: {
        avatar: [{ required: true, message: '头像不能为空', trigger: 'change' }],
        username: [
          { required: true, message: '请输入昵称', trigger: 'blur' }],
        phone: [{
          required: true,
          //  自定义校验约定validator
          //  rule:规则
          //  value:值
          //  callback:回调错误返回错误信息 正确callback
          validator: (rule, value, callback) => {
            if (!value) return callback(new Error('手机号不能为空'))
            // 正则判断手机号是否合法
            const reg = /^1[3456789][0-9]{9}$/
            if (!reg.test(value)) return callback(new Error('手机号不合法'))
            // 来到这里合法手机号
            callback()
          },
          trigger: 'blur'
        }
        ],
        email: [{
          required: true,
          //  自定义校验约定validator
          //  rule:规则
          //  value:值
          //  callback:回调错误返回错误信息 正确callback
          validator: (rule, value, callback) => {
            if (!value) return callback(new Error('邮箱不能为空'))
            // 正则判断邮箱是否合法
            // 在下一行禁用eslint，类似上一种方法，只是写的位置不同罢了,给eslint看的告诉他下一句不用管
            // eslint-disable-next-line
            const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
            if (!reg.test(value)) return callback(new Error('邮箱不合法'))
            // 来到这里合法手机号
            callback()
          },
          trigger: 'blur'
        }],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        code: [{ required: true, message: '请输入图形码', trigger: 'blur' }],
        rcode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      }
    }
  },
  watch: {
    // 监听 dialogVisible是否显示
    dialogVisible (newValue) {
      if (!newValue) {
        // 重置表单
        // 只清除带prop属性的,图片那里avatar为'',但是图片预览地址还在,所以我们要手动清除
        this.$refs.form.resetFields()
        this.imageUrl = ''
      }
    }
  },
  methods: {
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    // 上传头像成功
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      // console.log(res)
      if (res.code === 200) {
        //   赋值给avatar
        this.form.avatar = res.data.file_path
      }
    },
    // 上传头像前
    beforeAvatarUpload (file) {
    //   console.log(file)
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像不合法!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      this.imageObj.image = file
      return isJPG && isLt2M
    },
    // 图形码点击刷新事件
    getCode () {
      this.getCaptcha = process.env.VUE_APP_BASEURL + `/captcha?type=sendsms&uu=${new Date() - 0}`
    },
    // 获取验证码
    async getrcode () {
      // 校验手机号图形码是否正确,使用部分验证表单validateField
      let num = 0
      this.$refs.form.validateField(['phone', 'code'], errorMessage => {
        // console.log(errorMessage) 看看错误是什么
        // 判断无错误加1
        if (!errorMessage) {
          num++
        }
      })
      //   等于2说明要校验的表单都没错
      if (num === 2) {
        const res = await this.$axios.post('/sendsms', {
          code: this.form.code,
          phone: this.form.phone
        })
        // console.log(res)
        if (res.code === 200) {
          this.form.rcode = res.data.captcha
        } else {
          this.$message.error(res.message)
          // 刷新图形码
          this.getCode()
        }
      }
    },
    register () {
    // 全局校验
      this.$refs.form.validate(async valid => {
        if (!valid) return
        const res = await this.$axios.post('/register', this.form)
        console.log(res)
        if (res.code === 200) {
          // 提示注册成功
          this.$message.success('注册成功')
          // 关闭组件
          this.dialogVisible = false
        } else {
          // 提示错误
          this.$message.error('res.message')
          // 刷新图形码
          this.getCode()
        }
      })
    }
  }
}
</script>
<style lang="less">
.avatar-uploader {
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px !important;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
